#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天翼云WebDAV统一Web应用
基于FastAPI的统一Web服务，包含WebDAV、API接口和管理页面
"""

import os
import sys
from pathlib import Path
from typing import Optional, Dict, Any

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn

from src.common.unified_logging import get_logger, init_unified_logging
from src.web.webdav.fastapi_webdav_handler import create_fastapi_webdav_app
from src.vfs import VFSClient
from src.common.database import init_global_session, get_session
from src.models.cloud import CloudAccount
from src.vfs.virtual_file_system import VirtualFileSystem
from src.clouds_sdk.clouds_client import CloudsClient


def _create_clouds_client(enable_cache: bool = True) -> CloudsClient:
    """创建CloudsClient实例"""
    logger = get_logger('CloudsClientFactory')
    
    try:
        session = get_session()
        cloud_account = session.query(CloudAccount).filter_by(
            cloud_provider='tianyi',
            is_active=True
        ).first()
        
        if not cloud_account:
            logger.warning("未找到激活的天翼云盘账号")
            return None
        
        # 创建数据库持久化管理器
        from src.clouds_sdk.persistence import DatabasePersistenceManager
        persistence_manager = DatabasePersistenceManager()
        
        # 创建CloudsClient
        cache_config = {
            'path_cache_size': 10000,
            'folder_cache_size': 1000,
            'folder_cache_ttl': 300
        }
        clouds_client = CloudsClient(
            provider="tianyi_pc", 
            username=cloud_account.cloud_account,
            persistence_manager=persistence_manager,
            enable_cache=enable_cache,
            cache_config=cache_config
        )
        
        # 尝试登录
        login_success = clouds_client.load_account(
            provider="tianyi_pc",
            username=cloud_account.cloud_account,
            password=cloud_account.cloud_password,
            auto_load_persistent=True,
            save_persistent=True
        )
        
        if login_success:
            logger.info(f"CloudsClient创建成功，使用账号: {cloud_account.cloud_account}")
            return clouds_client
        else:
            logger.error(f"CloudsClient登录失败，账号: {cloud_account.cloud_account}")
            return None
            
    except Exception as e:
        logger.error(f"创建CloudsClient失败: {e}")
        return None
    finally:
        if 'session' in locals():
            session.close()


def _create_cloud_storage_manager(clouds_client) -> 'CloudStorageManager':
    """创建云存储管理器实例"""
    logger = get_logger('CloudStorageManagerFactory')
    
    try:
        from src.clouds_sdk.cloud_storage_scheduler import CloudStorageManager
        
        manager = CloudStorageManager(clouds_client, "/nas_cache")
        logger.info("云存储管理器创建成功")
        return manager
        
    except Exception as e:
        logger.error(f"创建云存储管理器失败: {e}")
        return None


def _create_vfs(clouds_client: CloudsClient) -> VirtualFileSystem:
    """创建VFS实例"""
    logger = get_logger('VFSFactory')
    
    try:
        # 创建VFS
        vfs_core = VirtualFileSystem(clouds_client=clouds_client)
        
        if clouds_client:
            # 获取账号信息
            session = get_session()
            cloud_account = session.query(CloudAccount).filter_by(
                cloud_provider='tianyi',
                is_active=True
            ).first()
            
            if cloud_account:
                vfs_core.set_tianyi_account(cloud_account.cloud_account)
                logger.info(f"VFS创建成功，使用账号: {cloud_account.cloud_account}")
            else:
                logger.warning("VFS创建成功，但未找到云盘账号")
            
            session.close()
        else:
            logger.warning("VFS创建成功，但CloudsClient为空")
        
        return vfs_core
        
    except Exception as e:
        logger.error(f"创建VFS失败: {e}")
        return VirtualFileSystem()


def create_app(
    vfs_client: Optional[VFSClient] = None,
    webdav_base_path: str = "/dav",
    config: Optional[Dict[str, Any]] = None
) -> FastAPI:
    """创建FastAPI应用"""
    
    # 初始化日志
    init_unified_logging("logs", "INFO")
    logger = get_logger('WebApp')
    
    # 创建FastAPI应用
    app = FastAPI(
        title="天翼云WebDAV服务",
        description="基于天翼云盘的WebDAV文件服务",
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc"
    )
    
    # 创建WebDAV应用
    webdav_app = create_fastapi_webdav_app(vfs_client, webdav_base_path.lstrip('/'))
    
    # 将WebDAV应用挂载到FastAPI
    app.mount(webdav_base_path, webdav_app)
    
    # 首页路由
    @app.get("/", response_class=HTMLResponse)
    async def home(request: Request):
        """首页"""
        return f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>天翼云WebDAV服务</title>
            <meta charset="utf-8">
            <style>
                body {{ font-family: Arial, sans-serif; margin: 40px; background-color: #f5f5f5; }}
                .container {{ max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
                h1 {{ color: #333; text-align: center; }}
                .info-box {{ background: #e8f4fd; padding: 20px; border-radius: 5px; margin: 20px 0; }}
                .service-box {{ background: #f0f8f0; padding: 20px; border-radius: 5px; margin: 20px 0; }}
                .api-box {{ background: #fff8e1; padding: 20px; border-radius: 5px; margin: 20px 0; }}
                .endpoint {{ font-family: monospace; background: #f5f5f5; padding: 5px 10px; border-radius: 3px; }}
                .status {{ color: #4caf50; font-weight: bold; }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>🚀 天翼云WebDAV服务</h1>
                
                <div class="info-box">
                    <h3>📊 服务状态</h3>
                    <p><span class="status">✅ 服务运行正常</span></p>
                    <p>版本: 1.0.0</p>
                    <p>基于: FastAPI + 天翼云盘</p>
                </div>
                
                <div class="service-box">
                    <h3>🌐 WebDAV服务</h3>
                    <p><strong>WebDAV地址:</strong> <span class="endpoint">{webdav_base_path}/</span></p>
                    <p><strong>测试用户:</strong> testuser / testpass123</p>
                    <p><strong>支持操作:</strong> 文件上传、下载、移动、复制、删除、目录操作</p>
                    <p><strong>协议支持:</strong> WebDAV Level 1 & 2</p>
                </div>
                
                <div class="api-box">
                    <h3>📋 API接口</h3>
                    <p><strong>API文档:</strong> <a href="/docs" target="_blank">/docs</a></p>
                    <p><strong>ReDoc文档:</strong> <a href="/redoc" target="_blank">/redoc</a></p>
                    <p><strong>健康检查:</strong> <a href="/health" target="_blank">/health</a></p>
                </div>
                
                <div class="info-box">
                    <h3>🔧 管理功能</h3>
                    <p>• 账号管理: 添加、删除、修改云盘账号</p>
                    <p>• 用户管理: WebDAV用户权限管理</p>
                    <p>• 系统监控: 服务状态和性能监控</p>
                    <p>• 数据管理: 文件系统完整性检查</p>
                </div>
            </div>
        </body>
        </html>
        """
    
    # 健康检查路由
    @app.get("/health")
    async def health_check():
        """健康检查"""
        try:
            # 检查数据库连接
            init_global_session()
            session = get_session()
            session.close()
            
            return {
                "status": "healthy",
                "service": "天翼云WebDAV服务",
                "version": "1.0.0",
                "database": "connected",
                "webdav": "available"
            }
        except Exception as e:
            logger.error(f"健康检查失败: {e}")
            raise HTTPException(status_code=503, detail="Service unhealthy")
    
    # 系统信息路由
    @app.get("/api/info")
    async def system_info():
        """系统信息"""
        try:
            # 获取云盘账号信息
            init_global_session()
            session = get_session()
            
            cloud_accounts = session.query(CloudAccount).filter_by(is_active=True).all()
            account_count = len(cloud_accounts)
            
            session.close()
            
            return {
                "service": "天翼云WebDAV服务",
                "version": "1.0.0",
                "webdav_path": webdav_base_path,
                "active_accounts": account_count,
                "features": [
                    "文件上传下载",
                    "文件移动复制",
                    "目录操作",
                    "302重定向下载",
                    "秒传检测",
                    "回收站功能"
                ]
            }
        except Exception as e:
            logger.error(f"获取系统信息失败: {e}")
            raise HTTPException(status_code=500, detail="Failed to get system info")
    
    # 账号管理API
    @app.get("/api/accounts")
    async def list_accounts():
        """列出云盘账号"""
        try:
            init_global_session()
            session = get_session()
            
            accounts = session.query(CloudAccount).filter_by(is_active=True).all()
            account_list = []
            
            for account in accounts:
                account_list.append({
                    "id": account.id,
                    "cloud_account": account.cloud_account,
                    "display_name": account.display_name,
                    "cloud_provider": account.cloud_provider,
                    "is_active": account.is_active,
                    "created_at": account.created_at.isoformat() if account.created_at else None
                })
            
            session.close()
            
            return {
                "accounts": account_list,
                "total": len(account_list)
            }
        except Exception as e:
            logger.error(f"列出账号失败: {e}")
            raise HTTPException(status_code=500, detail="Failed to list accounts")
    
    # 错误处理
    @app.exception_handler(404)
    async def not_found_handler(request: Request, exc: HTTPException):
        """404错误处理"""
        return JSONResponse(
            status_code=404,
            content={
                "error": "Not Found",
                "message": "请求的资源不存在",
                "path": str(request.url.path)
            }
        )
    
    @app.exception_handler(500)
    async def internal_error_handler(request: Request, exc: HTTPException):
        """500错误处理"""
        logger.error(f"内部服务器错误: {request.url.path} - {exc}")
        return JSONResponse(
            status_code=500,
            content={
                "error": "Internal Server Error",
                "message": "服务器内部错误"
            }
        )
    
    logger.info("FastAPI应用创建完成")
    return app


def start_webdav_server(
    host: str = "0.0.0.0",
    port: int = 8080,
    webdav_base_path: str = "/dav",
    reload: bool = False,
    log_level: str = "info",
    enable_cache: bool = True
):
    """启动WebDAV服务器"""
    
    # 初始化日志
    init_unified_logging("logs", log_level.upper())
    logger = get_logger('WebDAVServer')
    
    try:
        logger.info("=" * 60)
        logger.info("启动天翼云WebDAV统一Web服务")
        logger.info("=" * 60)
        
        # 显示缓存状态
        if enable_cache:
            logger.info("✅ 缓存功能: 已启用 (路径缓存: 10000条, 文件夹缓存: 1000条, TTL: 300秒)")
        else:
            logger.info("❌ 缓存功能: 已禁用")
        
        # 初始化数据库
        logger.info("初始化数据库连接...")
        init_global_session()
        
        # 解耦初始化：按照依赖关系顺序创建组件
        logger.info("开始解耦初始化组件...")
        
        # 1. 创建CloudsClient
        logger.info("1. 创建CloudsClient...")
        clouds_client = _create_clouds_client(enable_cache)
        
        # 2. 创建VFS
        logger.info("2. 创建VFS...")
        vfs_core = _create_vfs(clouds_client)
        
        # 3. 创建VFSClient
        logger.info("3. 创建VFSClient...")
        vfs_client = VFSClient(vfs_core)
        
        logger.info("✅ 组件解耦初始化完成")
        
        # 4. 启动云存储定时清理任务
        logger.info("4. 启动云存储定时清理任务...")
        cloud_storage_manager = _create_cloud_storage_manager(clouds_client)
        cloud_storage_manager.start_scheduler()
        
        logger.info("✅ 云存储定时清理任务已启动")
        
        # 创建FastAPI应用
        app = create_app(vfs_client=vfs_client, webdav_base_path=webdav_base_path)
        
        logger.info("FastAPI应用创建成功")
        logger.info(f"服务地址: http://{host}:{port}")
        logger.info(f"WebDAV服务: http://{host}:{port}{webdav_base_path}/")
        logger.info(f"API文档: http://{host}:{port}/docs")
        logger.info(f"管理页面: http://{host}:{port}/")
        logger.info("测试用户: testuser / testpass123")
        logger.info("按 Ctrl+C 停止服务")
        
        # 启动Uvicorn服务器
        try:
            uvicorn.run(
                app,
                host=host,
                port=port,
                reload=reload,
                log_level=log_level
            )
        finally:
            # 服务器停止时，停止定时清理任务
            if 'cloud_storage_manager' in locals() and cloud_storage_manager:
                logger.info("停止云存储定时清理任务...")
                cloud_storage_manager.stop_scheduler()
                logger.info("云存储定时清理任务已停止")
        
    except KeyboardInterrupt:
        logger.info("收到中断信号，正在停止服务...")
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")
        import traceback
        logger.error(f"详细错误信息: {traceback.format_exc()}")
        raise


if __name__ == "__main__":
    # 直接运行脚本时启动服务器
    start_webdav_server()
